package com.msun.auth.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

/**
 * @Description //TODO
 * @Date 2023/8/21 8:51
 * @Author guijie
 **/
public final class SysOaUtils {

    @Data
    public static class UserInfo {
        private Long id;
        private String uname;
        private String name;
        private Integer sex;
        private String sexName;
        private String jobTitle;
        private String mobile;
        private String email;
    }

    public static UserInfo syncUser(String uname) {
        String url = "http://oa.msunsoft.com:6800/msunErp-web/data/sync/getUsers?sync=imsp&loginname=" + uname;
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getIntValue("code") != 200) {
            return null;
        }
        JSONArray objs = jsonObject.getJSONArray("obj");
        if (CollUtil.isEmpty(objs)) {
            return null;
        }
        JSONObject obj = (JSONObject) objs.get(0);
        System.out.println(obj);
        UserInfo dto = new UserInfo();
        dto.setId(obj.getLong("id"));
        dto.setUname(obj.getString("loginname"));
        dto.setName(obj.getString("name"));
        dto.setSex(obj.getInteger("sex"));
        dto.setSexName(obj.getString("sexName"));
        dto.setMobile(obj.getString("mobile"));
        dto.setEmail(obj.getString("email"));
        JSONArray roles = obj.getJSONArray("roles");
        for (Object role : roles) {
            JSONObject r = (JSONObject) role;
            if (r.getIntValue("isDefault") == 1) {
                dto.setJobTitle(r.getString("name"));
                break;
            }
        }
        return dto;
    }
}
